package com.scut.fy.gateway.auth.service;

import cn.dev33.satoken.stp.StpInterface;
import com.scut.fy.common.core.util.Assert;
import com.scut.fy.gateway.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义权限验证接口扩展
 * @author JY
 */
@Component
public class StpInterfaceImpl implements StpInterface {
    @Resource
    private RedisTemplate redisTemplate;

    private SysRoleService sysRoleService;
    @Autowired
    public  StpInterfaceImpl(SysRoleService sysRoleService) {
        this.sysRoleService = sysRoleService;
    }
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        Assert.notNull(loginId, "用户id不能为空");
        // 暂时没用到这个，那就复用一下
        return this.getRoleList(loginId, loginType);
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        List<String> roleList = new ArrayList<>();
        Assert.notNull(loginId, "用户id不能为空");
        // 把object转为long
        long userId = Long.valueOf(String.valueOf(loginId)).longValue();
        // 通过userId,查出role集合，在过滤成id集合
        roleList = sysRoleService.findRolesByUser(userId)
                .stream().map(i -> i.getId().toString()).distinct().collect(Collectors.toList());
        return roleList;
    }
}
